import React, { useEffect, useState } from 'react';
import { Button, message, Select, Space } from 'antd';
import styles from './index.less';
import TjTable from '@/pages/ETrade/components/TjTable';
import { TjChart } from '@/pages/ETrade/components';
import { DownSquareOutlined, UploadOutlined, UpSquareOutlined } from '#/utils/antdIcons';
import { column, getChartOption, platformOptions, unitOptions, getTableData } from './helper';
import { connect } from 'umi';
import { postQueryShortForecastCurveAdjustment } from '../../service';
import { PageLoading } from '@/components';
import { HttpCode } from '#/utils/contacts';
import moment from 'moment';
import { TIME_96 } from '@/pages/ETrade/components/helper';
import { export_json_to_excel } from '@/utils/fileExport';
import { havePermissions } from '@/pages/ETrade/ShorttermForecastingRedesign/tool';

const StepTwoContent = (props) => {
  const { issuePlanTableData, searchForm, buttonPermissions } = props;

  const [isSpread, setIsSpread] = useState(false);
  const [platform, setPlatform] = useState(platformOptions[0]?.value);
  const [unit, setUnit] = useState(unitOptions[0].value);
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [chartOption, setChartOption] = useState({});
  const [record, setRecord] = useState(issuePlanTableData[0]);

  useEffect(() => {
    (async () => {
      const data = issuePlanTableData?.[0] || null;
      if (!data) {
        return;
      }
      await getIssueDetailData({
        adjustmentId: data.adjustmentId,
        executeStatus: data.executeStatus,
        issueRateId: data.issueRateId,
        forecastId: data.forecastId,
        side: platform,
        unit: unit,
        saveType: searchForm.saveType,
        stationId: searchForm.stationId,
        marketId: searchForm.marketId,
        startDate: searchForm.calendarDate,
        endDate: searchForm.calendarDate,
      });
    })();
  }, [unit, platform, searchForm, issuePlanTableData]);

  const getIssueDetailData = async (params = {}) => {
    setLoading(true);
    const res = await postQueryShortForecastCurveAdjustment(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const data = res?.data || {};
      const dateKey = moment(searchForm.calendarDate).format('YYYY.MM.DD');
      setTableData(getTableData(data, dateKey));
      setChartOption(getChartOption(data, dateKey, unit, searchForm.calendarDate));
    } else {
      message.error(res?.message || '获取申报详情数据失败');
    }
    setLoading(false);
  };

  const changeSpread = () => {
    setIsSpread(!isSpread);
  };

  const _onExport = () => {
    const result = havePermissions('IteraShortTermForcastExportButtton', buttonPermissions);
    if (result) {
      const data = tableData.map((i) => {
        const arr = [];
        arr.push(i.type);
        TIME_96.map((t) => arr.push(i[t]));
        return arr;
      });
      const _sideName = platformOptions.find((i) => i.value === platform)?.label || '';
      const _unitName = unitOptions.find((i) => i.value === unit)?.label || '';
      const params = {
        header: getColumns().map((i) => i.name),
        data,
        filename: `${searchForm.calendarDate}_${searchForm.provinceName}_${searchForm.stationName}
      申报详情${record?.issueTime}申报(${_sideName}-${_unitName})`,
      };
      export_json_to_excel(params);
    }
  };

  const changePlatform = (v) => {
    setPlatform(v);
  };

  const changeUnit = (v) => {
    setUnit(v);
  };

  const getColumns = () => {
    const arr = TIME_96.map((i) => ({
      name: i,
      code: i,
      width: 100,
    }));
    return [
      {
        name: '类型',
        code: 'type',
        width: 200,
      },
      ...arr,
    ];
  };

  const handleView = async (record) => {
    setRecord(record);
    await getIssueDetailData({
      adjustmentId: record.adjustmentId,
      executeStatus: record.executeStatus,
      issueRateId: record.issueRateId,
      forecastId: record.forecastId,
      side: platform,
      unit: unit,
      stationId: searchForm.stationId,
      saveType: searchForm.saveType,
      marketId: searchForm.marketId,
      startDate: searchForm.calendarDate,
      endDate: searchForm.calendarDate,
    });
  };

  const getPlanColumn = () => {
    let newColumn = _.cloneDeep(column);
    // 甘肃没有申报平台
    if (searchForm.marketId === 'PXBGS') {
      newColumn = newColumn.filter((i) => i.code !== 'wfName');
    }
    // 山西交易数据没有下发主站
    if (searchForm.saveType === 1 && searchForm.marketId === 'PHBSX') {
      newColumn = newColumn.map((i) =>
        i.code === 'dataSourceName' ? { ...i, render: (v) => '-' } : i,
      );
    }
    return [
      ...newColumn,
      {
        code: 'operation',
        name: '操作',
        width: 140,
        align: 'center',
        render(v, record) {
          return <a onClick={() => handleView(record)}>查看</a>;
        },
      },
    ];
  };

  return (
    <div className={styles.body}>
      <div className={styles.plan}>
        <div className={styles.title}>申报计划</div>
        <TjTable
          style={{ marginTop: 16 }}
          columns={getPlanColumn()}
          dataSource={issuePlanTableData}
        />
      </div>
      <div className={styles.detail}>
        <div className={styles.detailHead}>
          <div className={styles.title}>申报详情</div>
          <Space size={16}>
            <Select
              disabled={loading}
              className={styles.select}
              value={platform}
              options={platformOptions}
              onChange={changePlatform}
            />
            <Select
              disabled={loading}
              className={styles.select}
              value={unit}
              options={unitOptions}
              onChange={changeUnit}
            />
            <Button
              disabled={loading}
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              onClick={_onExport}
            >
              导出
            </Button>
            <div onClick={changeSpread} className={styles.spread}>
              <Space>
                {isSpread ? (
                  <>
                    <UpSquareOutlined />
                    <span>收起</span>
                  </>
                ) : (
                  <>
                    <DownSquareOutlined />
                    <span>展开</span>
                  </>
                )}
              </Space>
            </div>
          </Space>
        </div>
        <div className={styles.content}>
          {loading ? (
            <PageLoading />
          ) : (
            <>
              <div style={{ height: isSpread ? '48%' : '100%' }}>
                <TjChart option={chartOption} group={'F'} />
              </div>
              <div
                style={{ display: isSpread ? 'block' : 'none', height: '50%', overflow: 'auto' }}
              >
                <TjTable columns={getColumns()} dataSource={tableData} />
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ shortTermForecastingRedesignV2, global }) => ({
  issuePlanTableData: shortTermForecastingRedesignV2.issuePlanTableData,
  searchForm: shortTermForecastingRedesignV2.searchForm,
  buttonPermissions: global.configure.buttonPermissions,
}))(StepTwoContent);
